package com.example.springbootelasticjob.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.example.autoconfig.ElasticSimpleJob;
import com.example.springbootelasticjob.model.Order;
import com.example.springbootelasticjob.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * @ClassName OrderCancleJob
 * @Description TODO
 * @Author wyp
 * @Date 2023/8/16 15:20
 * @Version 1.0
 */
@Slf4j
//@ElasticSimpleJob(
//        jobName = "orderCancleJob",
//        cron = "0/15 * * * * ?",
//        shardingTotalCount = 2,
//        overwrite = true
//)
public class OrderCancleJob implements SimpleJob {

    @Resource
    private OrderService orderService;

    @Override
    public void execute(ShardingContext shardingContext) {
        log.info("我是分片项: " + shardingContext.getShardingItem() + "," +
                "总分片数: " + shardingContext.getShardingTotalCount());
        Calendar now = Calendar.getInstance();
        now.add(Calendar.SECOND, -30);
        List<Order> orders = orderService.getOrder(now.getTime(), shardingContext.getShardingTotalCount(), shardingContext.getShardingItem());
        if (orders != null && orders.size() > 0) {
            ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 10, 30, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
            for (Order order : orders) {
                executor.execute(() -> {
                    Integer orderId = order.getId();
                    Date updateTime = order.getUpdateTime();
                    int status = 3;
                    String updateUser = "system";
                    Date updateNow = new Date();
                    orderService.cancelOrder(orderId, updateTime, status, updateUser, updateNow);
                });

            }
        }
    }
}
